package com.shengdong.water.feature.management.monitor

import android.util.Log
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import coil.util.Logger
import com.alibaba.android.arouter.facade.annotation.Route
import com.shengdong.water.R
import com.shengdong.water.base.BaseVMActivity
import com.shengdong.water.code.adapter.VideoMonitorAdapter
import com.shengdong.water.code.adapter.VideoTreeAdapter
import com.shengdong.water.code.bean.NodeType
import com.shengdong.water.code.bean.TreeNode
import com.shengdong.water.code.bean.VIEW_TYPE_PARENT
import com.shengdong.water.code.bean.VIEW_TYPE_VIDEO
import com.shengdong.water.code.config.RouterConfig
import com.shengdong.water.code.router.RouterManager
import com.shengdong.water.code.viewmodel.VideoMonitorViewModel
import com.shengdong.water.databinding.ActivityVideoMonitorBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@Route(path = RouterConfig.Management.VIDEO_MONITOR_PATH)
@AndroidEntryPoint
class VideoMonitorActivity : BaseVMActivity<ActivityVideoMonitorBinding, VideoMonitorViewModel>(){

    override fun getLayoutId() = R.layout.activity_video_monitor
    override fun getViewModelClass() = VideoMonitorViewModel::class.java

//    val monitorAdapter  = VideoMonitorAdapter()
     var videoTreeAdapter = VideoTreeAdapter()

    override fun initViews() {
        super.initViews()
        setTitle("现场监控视频")
        binding.viewModel = viewModel

        binding.recyclerMonitors.layoutManager = LinearLayoutManager(this)
        binding.recyclerMonitors.setHasFixedSize(true)
//        binding.recyclerMonitors.adapter = monitorAdapter
        setupListener()
        binding.recyclerMonitors.adapter = videoTreeAdapter

    }

    private fun setupListener() {
//        monitorAdapter.setOnItemClickListener { item, ops -> {
//            Log.e("TAG", "setupListener: ${item.videoUrl}")
//            RouterManager.build(RouterConfig.Management.VIDEO_PLAYER_PATH)
//                .withString("videoUrl", item.videoUrl)
//                .navigate()
//        } }
        //        videoTreeAdapter = VideoTreeAdapter(
//            onItemClickCallback = { node ->
//                // 这个回调可以用于处理特定项的点击，例如视频项
//                if (node.type == NodeType.VIDEO && node.value != null) {
//                    //点击播放视频
//                }
//            }
//        )
        videoTreeAdapter.setOnItemClickListener { node, position ->
            if (node.type == NodeType.PARENT) {
                // 点击的是父节点，执行展开/折叠
                videoTreeAdapter.toggleNodeExpansion(node)
            } else if (node.type == NodeType.VIDEO) {
                if(node.value != null){
                    // 点击的是视频节点，执行播放视频操作
                    Log.e("TAG", "setupListener: ${node.value}")
                    RouterManager.build(RouterConfig.Management.VIDEO_PLAYER_PATH)
                        .withString("videoCam", node.value)
                        .navigate()
                }
                // 如果 onItemClickCallback 已经处理了视频点击，这里可以不重复处理
                // 或者在这里统一处理所有点击，然后分发
//                 videoTreeAdapter.onItemClickCallback(node) // 可以选择调用
            }
        }
    }


    override fun initData() {
        super.initData()
//        viewModel.getAllOutlets()
        viewModel.getRegionStructure()
    }

    override fun observeData() {
        super.observeData()
        lifecycleScope.launch {
//            viewModel.outlets.collect { outlets ->
//                if (outlets.isEmpty()) {
//                    binding.recyclerMonitors.setEmptyView(binding.layoutEmpty.root)
//                    return@collect
//                }
//                monitorAdapter.setItems(outlets)
//            }
            viewModel.regionStructure.collect { regionStructure ->
                if (regionStructure.isEmpty()) {
                    binding.recyclerMonitors.setEmptyView(binding.layoutEmpty.root)
                    videoTreeAdapter.setTreeData(emptyList())
                    return@collect
                }
                val treeNodes = convertToTreeNodes(regionStructure)
                videoTreeAdapter.setTreeData(treeNodes)
            }
        }
    }

    private fun convertToTreeNodes(data: List<TreeNode>): List<TreeNode> {
        // 实现转换逻辑
        // 例如，递归遍历你的数据，创建 TreeNode 对象，并设置好 children, type, isExpanded, viewType 等
        fun mapToTreeNode(item: TreeNode, currentLevel: Int): TreeNode {
            val children = item.children?.map { mapToTreeNode(it, currentLevel + 1) }?.toMutableList()
            val nodeType = if (children.isNullOrEmpty()) NodeType.VIDEO else NodeType.PARENT
            return TreeNode(
                label = item.label,
                type = nodeType,
                children = children,
                value = if (nodeType == NodeType.VIDEO) item.value else null,
                isExpanded = false, // 初始折叠，或根据你的业务逻辑设置
                level = currentLevel,
                viewType = if (nodeType == NodeType.PARENT) VIEW_TYPE_PARENT else VIEW_TYPE_VIDEO
            )
        }
        return data.map { mapToTreeNode(it, 0) }
    }
}